<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 商品管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input
          v-model="query.GoodsName"
          placeholder="商品名称"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch"
          >搜索
        </el-button>
        <el-button type="primary" @click="addGoods">新增商品 </el-button>
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <!-- <el-table-column
                        type="selection"
                        width="55"
                        align="center"
                ></el-table-column> -->
        <el-table-column
          prop="goodsId"
          label="ID"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column prop="goodsName" label="商品名称"></el-table-column>
        <el-table-column prop="goodsPrice" label="价格"></el-table-column>
        <!-- <el-table-column label="账户余额">
                            <template #default="scope">￥{{ scope.row.money }}</template>
                        </el-table-column> -->
        <el-table-column label="商品(查看大图)" align="center">
          <template #default="scope">
            <el-image
              class="table-td-thumb"
              :src="'https://www.cfxs.work/api/file' + scope.row.goodsImg"
              :preview-src-list="[
                'https://www.cfxs.work/api/file' + scope.row.goodsImg,
              ]"
            ></el-image>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="address" label="地址"></el-table-column> -->
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.goodsState === 0
                  ? 'success'
                  : scope.row.goodsState === 1
                  ? 'danger'
                  : ''
              "
              >{{ scope.row.goodsState === 0 ? "已上架" : "已下架" }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- <el-table-column prop="userCreateTime" label="注册时间"></el-table-column> -->
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑
            </el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageNum"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" v-model="editVisible" width="30%">
      <el-form ref="form" :model="form" label-width="70px">
        <el-form-item label="商品名" label-width="100">
          <el-input v-model="form.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="商品类别" label-width="100">
          <el-select v-model="form.goodsCategoryId" placeholder="请选择">
            <el-option
              v-for="item in categoryList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" label-width="100">
          <el-input v-model="form.goodsPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品状态(1:下架,0:上架)" label-width="100">
          <el-input v-model="form.goodsState"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" label-width="100">
          <el-upload
            class="avatar-uploader"
            action=""
            :http-request="fileUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-change="upload"
          >
            <img
              v-if="form.goodsImg"
              :src="'https://www.cfxs.work/api/file' + form.goodsImg"
              style="witdh: 150px; height: 150px"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" label-width="100">
          <el-input v-model="form.goodsDesc"></el-input>
        </el-form-item>
        <el-form-item label="商品属性(商品属性ID)" label-width="100">
          <el-input v-model="form.goodsSkuId"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="新增" v-model="addGoodsVisible" width="30%">
      <el-form ref="form" :model="goods" label-width="70px">
        <el-form-item label="商品名" label-width="100">
          <el-input v-model="goods.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="商品类别" label-width="100">
          <el-select v-model="goods.goodsCategoryId" placeholder="请选择">
            <el-option
              v-for="item in categoryList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" label-width="100">
          <el-input v-model="goods.goodsPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品状态(1:下架,0:上架)" label-width="100">
          <el-input v-model="goods.goodsState"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" label-width="100">
          <el-upload
            class="avatar-uploader"
            action=""
            :http-request="fileUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-change="addupload"
          >
            <img
              v-if="goods.goodsImg"
              :src="'https://www.cfxs.work/api/file' + goods.goodsImg"
              style="witdh: 150px; height: 150px"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" label-width="100">
          <el-input v-model="goods.goodsDesc"></el-input>
        </el-form-item>
        <el-form-item label="商品属性(商品属性ID)" label-width="100">
          <el-input v-model="goods.goodsSkuId"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addGoodsVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveGoods">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// import Schart from 'vue-schart';
import request from "../api/index";
import axios from "axios";

export default {
  name: "basetable",
  data() {
    return {
      query: {
        GoodsName: "",
        pageNum: 1,
      },
      tableData: [],
      multipleSelection: [],
      delList: [],
      editVisible: false,
      addGoodsVisible: false,
      pageTotal: 0,
      form: {},
      idx: -1,
      id: -1,
      categoryList: [],
      goodsSkuList: [],
      goods: {
        goodsId: null,
        goodsName: null,
        goodsSkuId: null,
        goodsDesc: null,
        goodsImg: null,
        goodsNum: null,
        goodsPrice: null,
        goodsCategoryId: null,
        goodsState: 0,
      },
    };
  },
  created() {
    this.getData();
    this.getCategory();
    this.getGoodsSku();
  },
  methods: {
    // 获取商品列表
    getData() {
      request.getGoodsList(this.query).then((res) => {
        this.tableData = res.data.records;
        this.pageTotal = res.data.total;
      });
    },
    getCategory() {
      request.getCategoryList().then((res) => {
        this.categoryList = res.data;
      });
    },
    getGoodsSku() {
      request.getGoodsSku().then((res) => {
        this.goodsSkuList = res.data;
      });
    },
    addGoods() {
      this.addGoodsVisible = true;
    },
    // 触发搜索按钮
    handleSearch() {
      this.getData();
    },
    // 删除操作
    handleDelete(index, row) {
      console.log(index, row);
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          let query = {
            goodsId: row.goodsId,
          };

          request.removeGoods(query).then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.tableData.splice(index, 1);
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {});
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delAllSelection() {
      const length = this.multipleSelection.length;
      let str = "";
      this.delList = this.delList.concat(this.multipleSelection);
      for (let i = 0; i < length; i++) {
        str += this.multipleSelection[i].name + " ";
      }
      this.$message.error(`删除了${str}`);
      this.multipleSelection = [];
    },
    // 编辑操作
    handleEdit(index, row) {
      this.idx = index;
      this.form = row;

      this.editVisible = true;
    },
    saveGoods() {
      console.log(this.goods);
      let query = {
        goods: this.goods,
      };
      request.addGoods(query).then((res) => {
        if (res.code === 200) {
          this.addVisible = false;
          this.$message.success(`新增商品成功`);

          this.getData();
        } else {
          this.$message.error("新增商品失败");
        }
      });
    },
    // 保存编辑
    saveEdit() {
      this.editVisible = false;
      this.goods.goodsId = this.form.goodsId;
      this.goods.goodsName = this.form.goodsName;
      this.goods.goodsSkuId = this.form.goodsSkuId;
      this.goods.goodsDesc = this.form.goodsDesc;
      this.goods.goodsImg = this.form.goodsImg;
      this.goods.goodsNum = this.form.goodsNum;
      this.goods.goodsPrice = this.form.goodsPrice;
      this.goods.goodsCategoryId = this.form.goodsCategoryId;
      this.goods.goodsState = this.form.goodsState;
      console.log(JSON.stringify(this.goods));
      let query = {
        goods: this.goods,
      };
      request.editGoods(query).then((res) => {
        if (res.code === 200) {
          this.$message.success(`修改第 ${this.idx + 1} 行成功`);
          this.getData();
        } else {
          this.$message.error("修改失败");
        }
      });
    },
    // 分页导航
    handlePageChange(val) {
      console.log(val);
      this.query.pageNum = val;
      this.getData();
    },
    fileUpload(file) {
      // console.log("!")
      console.log(file);
    },

    upload(file) {
      let formData = new FormData();
      formData.append("file", file.raw);
      axios
        .request({
          url: "https://www.cfxs.work/api/admin/goods/upload/",
          method: "post",
          data: formData,
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.form.goodsImg = res.data.data;
            this.$message.success("上传成功");
          } else {
            this.$message.error("上传失败");
          }
        });
    },
    addupload(file) {
      let formData = new FormData();
      formData.append("file", file.raw);
      axios
        .request({
          url: "https://www.cfxs.work/api/admin/goods/upload/",
          method: "post",
          data: formData,
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.goods.goodsImg = res.data.data;
            this.$message.success("上传成功");
          } else {
            this.$message.error("上传失败");
          }
        });
    },
    beforeAvatarUpload(file) {
      console.log(file.type);
      const isJPG = file.type === "image/jpeg";

      const isLt2M = file.size / 1024 / 1024 < 4;
      if (!isLt2M) {
        this.$message.error("商品图片大小不能超过 4MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="scss" scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>